package evolution.tests;

import org.junit.Assert;
import org.junit.Test;

import evolution.individual.Individual;
import evolution.individual.RealCodedIndividual;
import evolution.operation.migration.MigrationHelper;

public class MigrationTests {

	@Test
	public void getNBestTest() {
		int n = 2;
		int populationSize = 5;
		Individual[] population = new Individual[populationSize];

		Individual best = new RealCodedIndividual();
		best.setFitness(100);
		Individual second = new RealCodedIndividual();
		second.setFitness(80);
		Individual third = new RealCodedIndividual();
		third.setFitness(60);
		Individual fourth = new RealCodedIndividual();
		fourth.setFitness(40);
		Individual fifth = new RealCodedIndividual();
		fifth.setFitness(20);

		population[0] = third;
		population[1] = second;
		population[2] = fifth;
		population[3] = fourth;
		population[4] = best;

		Individual[] expectedBest = new Individual[n];
		expectedBest[0] = best;
		expectedBest[1] = second;

		Individual[] nBest = MigrationHelper.getNBest(population, n);
		Assert.assertArrayEquals(expectedBest, nBest);
	}

	@Test
	public void replaceWorstTest() {
		int n = 2;
		int populationSize = 5;
		Individual[] population = new Individual[populationSize];

		Individual best = new RealCodedIndividual();
		best.setFitness(100);
		Individual second = new RealCodedIndividual();
		second.setFitness(80);
		Individual third = new RealCodedIndividual();
		third.setFitness(60);
		Individual fourth = new RealCodedIndividual();
		fourth.setFitness(40);
		Individual fifth = new RealCodedIndividual();
		fifth.setFitness(20);

		population[0] = third;
		population[1] = second;
		population[2] = fifth;
		population[3] = fourth;
		population[4] = best;

		Individual[] expectedBest = new Individual[n];
		expectedBest[0] = best;
		expectedBest[1] = second;

		Individual immigrant1 = new RealCodedIndividual();
		immigrant1.setFitness(500);
		immigrant1.setChromosome(new double[0]);

		Individual immigrant2 = new RealCodedIndividual();
		immigrant2.setFitness(400);
		immigrant2.setChromosome(new double[0]);

		Individual[] immigrants = new Individual[n];
		immigrants[0] = immigrant1;
		immigrants[1] = immigrant2;

		Individual[] expectedPopulation = population.clone();
		expectedPopulation[3] = immigrant1;
		expectedPopulation[4] = immigrant2;

		MigrationHelper.replaceLastN(immigrants, population, n);
		Assert.assertArrayEquals(expectedPopulation, population);

		expectedPopulation = population.clone();
		expectedPopulation[1] = immigrant1;
		expectedPopulation[2] = immigrant2;

		MigrationHelper.replaceLastN(immigrants, population, n, 2);
		Assert.assertArrayEquals(expectedPopulation, population);
	}
}
